<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="标题" prop="title">
      <el-input v-model="dataForm.title" placeholder="主题"></el-input>
    </el-form-item>
    <el-form-item label="消息权限" prop="msgType">
      <el-select v-model="dataForm.msgType" placeholder="请选择" @change="initData(dataForm.msgType)">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </el-form-item>
      <el-form-item size="mini" label="数据权限" v-show="dataForm.msgType==3">
        <el-tree
          :data="deptList"
          :props="deptListTreeProps"
          node-key="deptId"
          ref="deptListTree"
          :default-expand-all="true"
          show-checkbox
        ></el-tree>
      </el-form-item>
      <el-row>
        <el-col :span="9" >
          <el-form-item label="推送方式" prop="msgPushType">
            <template>
              <el-radio v-model="dataForm.msgPushType" label="1">立即推送</el-radio>
              <el-radio v-model="dataForm.msgPushType" label="2">定时推送</el-radio>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="11" :offset="4" v-if="dataForm.msgPushType==2">
          <el-form-item label="推送时间" prop="msgPushTime" >
            <el-date-picker
              v-model="dataForm.msgPushTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              default-time="12:00:00">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    <el-form-item label="有效时间" prop="msgExpireTime">
      <el-date-picker
        v-model="dataForm.msgExpireTime"
        type="datetime"
        placeholder="选择日期时间"
        value-format="yyyy-MM-dd HH:mm:ss"
        default-time="12:00:00">
      </el-date-picker>

    </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="dataForm.content"
          show-word-limit
          :rows="5"
        >
        </el-input>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>

  import { treeDataTranslate } from "@/utils";
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          msgInfoId: 0,
          title: '',
          content: '',
          msgType: '1',
          msgPushType: '1',
          msgPushTime: '',
          msgExpireTime: ''
        },
        deptList: [],
        daptListOld:[],
        deptListTreeProps: {
          label: "deptName",
          children: "children"
        },
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        options: [
          {
            value: "1",
            label: "本部门数据权限"
          },
          {
            value: "2",
            label: "本部门及以下数据权限"
          },
          {
            value: "3",
            label: "自定数据权限"
          }
        ],
        tempKey: -666666,
        dataRule: {
          title: [
            { required: true, message: '主题不能为空', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '内容不能为空', trigger: 'blur' }
          ],
          msgType: [
            { required: true, message: '消息类型 1.部门数据权限 2.部门及以下数据权限 3.自定义数据权限不能为空', trigger: 'blur' }
          ],
          msgPushType: [
            { required: true, message: '推送方式 1.立即推送 2.定时推送不能为空', trigger: 'blur' }
          ],
          msgPushTime: [
            { required: true, message: '推送时间不能为空', trigger: 'blur' }
          ],
          msgExpireTime: [
            { required: true, message: '有效时间不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      init (id) {
        this.dataForm.msgInfoId = id || 0
        this.visible = true
        this.$http({
          url: this.$http.adornUrl("/sys/dept/select"),
          method: "get",
          params: this.$http.adornParams()
        }).then(({ data }) => {
          //初始化装载数据
          this.deptList = treeDataTranslate(data.deptList, "deptId");
          this.$nextTick(() => {
            this.$refs.deptListTree.setCheckedKeys([]);
            this.$refs['dataForm'].resetFields()
          });
          if (this.dataForm.msgInfoId) {
            this.$http({
              url: this.$http.adornUrl(`/msg/msginfo/info/${this.dataForm.msgInfoId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.title = data.msgInfo.title
                this.dataForm.content = data.msgInfo.content
                this.dataForm.msgType = data.msgInfo.msgType+''
                this.dataForm.msgPushType = data.msgInfo.msgPushType+''
                this.dataForm.msgPushTime = data.msgInfo.msgPushTime
                this.dataForm.msgExpireTime = data.msgInfo.msgExpireTime
                var idx = data.msgInfo.deptIdList.indexOf(this.tempKey);
                if(data.msgInfo.msgType==3) {
                  this.$refs.deptListTree.setCheckedKeys(data.msgInfo.deptIdList);
                }
                if (idx !== -1) {
                  data.msgInfo.deptIdList.splice(
                    idx,
                    data.msgInfo.deptIdList.length - idx
                  );
                }
              }
            })
          }
        })
      },
      initData(value){
        if(value==3){
          this.$refs.deptListTree.setCheckedKeys(this.daptListOld);
        }
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/msg/msginfo/${!this.dataForm.msgInfoId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'msgInfoId': this.dataForm.msgInfoId || undefined,
                'title': this.dataForm.title,
                'content': this.dataForm.content,
                'msgType': this.dataForm.msgType,
                'msgPushType': this.dataForm.msgPushType,
                'msgPushTime': this.dataForm.msgPushTime,
                'msgExpireTime': this.dataForm.msgExpireTime,
                'deptIdList':this.dataForm.msgType==3? [].concat(
                  this.$refs.deptListTree.getCheckedKeys(),
                  [this.tempKey]
                ):[]
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
